<template>
  <div ref="password" class="password">
    <van-overlay :show="showKeyboard">
      <div class="password-box" :class="failtxt ? 'bottom' : ''">
        <van-icon name="cross" @click="hide" />
        <div class="label">请输入支付密码</div>
        <div class="describe" v-if="describe">{{ describe }}</div>
        <van-loading v-if="loading" />
        <van-password-input
          v-else
          :value="value"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <div class="fail" v-if="failtxt">{{ failtxt }}</div>
      </div>
    </van-overlay>
    <van-number-keyboard v-model="value" :show="showKeyboard" @blur="hide" />
  </div>
</template>
<script>
import { PasswordInput, NumberKeyboard, Overlay, Icon, Loading } from "vant";
export default {
  components: {
    [PasswordInput.name]: PasswordInput,
    [NumberKeyboard.name]: NumberKeyboard,
    [Overlay.name]: Overlay,
    [Icon.name]: Icon,
    [Loading.name]: Loading,
  },
  props: {
    describe: {
      type: String,
    },
  },
  data() {
    return {
      value: "",
      showKeyboard: false,
      failtxt: "",
      loading: true,
    };
  },
  created() {
    this.$nextTick(() => {
      const body = document.querySelector("body");
      if (body.append) {
        body.append(this.$refs.password);
      } else {
        body.appendChild(this.$refs.password);
      }
    });
  },
  destroyed: function () {
    if (this.$el) this.$el.parentNode.removeChild(this.$el);
  },
  methods: {
    show() {
      this.showKeyboard = true;
      this.loading = false;
      this.value = "";
      this.failtxt = "";
    },
    fail(text) {
      this.failtxt = text;
      this.value = "";
      this.loading = false;
    },
    hide() {
      this.showKeyboard = false;
      this.$emit("autoplay");
    },
  },
  watch: {
    value(value) {
      if (value.length === 6) {
        this.$emit("BuyData", value);
        this.loading = true;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.password {
  position: relative;
  z-index: 99999;
}
.van-overlay {
  background-color: rgba(0, 0, 0, 0.5);
}
.password-box {
  position: fixed;
  top: 10vh;
  left: 0;
  right: 0;
  width: 280px;
  margin: 0 auto;
  background: #fff;
  border-radius: 5px;
  padding: 40px 17px;
  .label {
    margin: 0 0 0 6px;
    font-size: 16px;
    line-height: 30px;
  }
  .describe {
    margin: 0 0 0 6px;
    height: 17px;
    font-size: 12px;
    font-weight: 400;
    color: #333333;
    line-height: 17px;
  }
  .van-icon {
    position: absolute;
    top: 0;
    left: 0;
    padding: 12px;
    font-size: 12px;
    color: #999999;
  }
  .van-password-input {
    margin: 13px auto 0 auto;
  }
  .fail {
    margin-top: 19px;
    font-size: 12px;
    text-align: center;
    color: #ee0a24;
  }
  .van-loading {
    text-align: center;
    height: 50px;
    line-height: 50px;
  }
  &.bottom {
    padding-bottom: 20px;
  }
}
</style>